package com.mall.shiro;


import com.domain.User;
import com.mapper.primary.UserMapper;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;


import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

public class ShiroRealm extends AuthorizingRealm {

    @Resource
    UserMapper userMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("权限");
//        User user = (User) SecurityUtils.getSubject().getPrincipal();
//        int userId = user.getId();
        SimpleAuthorizationInfo info =  new SimpleAuthorizationInfo();
        Set<String> permissionSet = new HashSet<>();
        permissionSet.add("权限添加");
        info.setStringPermissions(permissionSet);
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        System.out.println("用户");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        System.out.println("token >> " + token);

        String account = token.getUsername();
        String password = String.valueOf(token.getPassword());

        System.out.println("account > " + account);
        System.out.println("password > " + password);

        User user;
          user  = userMapper.selectByUsername(account);
        System.out.println("user > " + user);
        if(!user.getPassword().equals(password)){
            throw new AccountException("帐号或密码不正确！");
        }

        System.out.println("name > " + getName());
        return new SimpleAuthenticationInfo(account, password ,getName());
    }
}
